/*
 *	(*^。^*) TFrameWork License (*^。^*)
 */

/*
 *  Title :
 *
 *  Description :
 *
 *
 *  Date :
 *
 *  Author : DengPing
 *
 *  Modify :
 */

using UnityEngine;

namespace TFrameWork.Module.ActionEditor
{
    public class CustomOnParticleTrack : CustomOnRecordTrack,IOnParticleTrack
    {
        private Transform _particleRoot;
        private GameObject _particle;

        private PrefabEvent _prefabEvent;

        private Transform playerRoot;
        private Transform recordRoot;
        
        public override void Init(TimeLineAction timeLineAction)
        {
            base.Init(timeLineAction);
            _particleRoot = new GameObject(nameof(CustomOnParticleTrack)).transform;
            _particleRoot.position = Vector3.zero;
            _particleRoot.rotation = Quaternion.identity;
            _particleRoot.localScale = Vector3.one;
            _particleRoot.hideFlags = HideFlags.DontSave;
        }
        
        public override void OnStart(TrackEventBase data)
        {
            base.OnStart(data);
            _prefabEvent = data as PrefabEvent;
            //用于测试就使用编辑器加载
            playerRoot = timeLineAction.GetComponent<Transform>();
            var trans =  playerRoot.GetComponentsInChildren<Transform>();
            foreach (var tran in trans)
            {
                if (tran.name == _prefabEvent.rocordTransformName)
                {
                    recordRoot = tran;
                }
            }
            _particle = Object.Instantiate(_prefabEvent.prefab, _particleRoot, false);
            _particle.GetComponentInChildren<ParticleSystem>().Play();

        }

        public override void OnUpdate(int currentFrame)
        {
            base.OnUpdate(currentFrame);
            if(_particle == null) return;
            if (_prefabEvent.recordEventDatas.TryGetValue(currentFrame, out var record))
            {
                //客户端可以直接找到动画显示节点进行绑定赋值                
                _particle.transform.position = recordRoot.position;
                _particle.transform.rotation = recordRoot.rotation;

                //服务器 没有动画显示节点。可以更具根节点位置和record保存的子节点的变换矩阵计算 当前位置
            }
        }
        
        public override void OnFinish()
        {
            if(_particle == null) return;
            Object.Destroy(_particle);
        }
    }
}